﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kojarskiy.Models;

namespace Kojarskiy.Core
{
    public static class Localization
    {
        public static string GetLocalizedValue(string key)
        {
            var context = new KojarskiyDbEntities();
            var value = context.Localizations.FirstOrDefault(x => x.Key == key && x.Culture == Current);
            if (value != null)
            {
                return value.Value;
            }
            return "";
        }
        public static string Current
        {
            get
            {
                if (HttpContext.Current.Session == null) return "ru";

                var httpCookie = HttpContext.Current.Request.Cookies["Language"];

                if (HttpContext.Current.Session["Language"] == null)
                {
                    HttpContext.Current.Session["Language"] = "ru";
                }

                if (httpCookie != null && !String.IsNullOrEmpty(httpCookie.Value))
                {
                    if (httpCookie.Value == "Ru-ru") httpCookie.Value = "ru";
                    if (httpCookie.Value == "En-us") httpCookie.Value = "en";
                    if (httpCookie.Value == "De-de") httpCookie.Value = "de";
                    if (httpCookie.Value == "Ua-ua") httpCookie.Value = "ua";
                    return httpCookie.Value;
                }
                else
                {
                    var cookie = new HttpCookie("Language");
                    cookie.Value = Convert.ToString(HttpContext.Current.Session["Language"]);
                    cookie.Expires = DateTime.UtcNow.AddYears(10);
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
                return HttpContext.Current.Session["Language"].ToString();
            }
            set
            {
                HttpContext.Current.Session["Language"] = value;

                if (HttpContext.Current.Response.Cookies["Language"] != null)
                    HttpContext.Current.Response.Cookies.Remove("Language");

                var cookie = new HttpCookie("Language");
                cookie.Value = Convert.ToString(value);
                cookie.Expires = DateTime.UtcNow.AddYears(10);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }
    }
}